package org.lichsword.ux.util;

import java.awt.BorderLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;

public class FileTransferHandler extends TransferHandler {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8216108560956512822L;
	
	private JList filePathList;

	public FileTransferHandler(JList filePathList) {
		this.filePathList = filePathList;
	}

	public boolean importData(JComponent c, Transferable t) {
		try {
			List files = (List) t
					.getTransferData(DataFlavor.javaFileListFlavor);
			addFilesToFilePathList(files);
			return true;
		} catch (UnsupportedFlavorException ufe) {
			ufe.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean canImport(JComponent c, DataFlavor[] flavors) {
		for (int i = 0; i < flavors.length; i++) {
			if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
				return true;
			}
		}
		return false;
	}

	private void addFilesToFilePathList(List files) {
		DefaultListModel model = new DefaultListModel();
		for (Iterator iter = files.iterator(); iter.hasNext();) {
			File file = (File) iter.next();
			model.addElement(file.getPath());
		}
		this.filePathList.setModel(model);
	}

	public static void main(String[] args) {
		JList filePathList = new JList();
		filePathList.setTransferHandler(new FileTransferHandler(filePathList));

		JFrame f = new JFrame("拖动文件到这个窗口里面 ");
		f.getContentPane().add(new JScrollPane(filePathList),
				BorderLayout.CENTER);
		f.pack();
		f.setLocationRelativeTo(null);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
	}
}
